<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace common\behavior;

use common\model\ProjectModel;
use common\model\TaskModel;
use common\service\CommonService;
use common\service\OrderService;
use common\service\StatusService;
use Exception;


/**
 * 任务状态监听
 */
class TaskStatusAfterUpdateBehavior
{

    /**
     * 运行同步的任务状态
     * @var array|int[]
     */
    public array $updateCodeStatus = [
        'final'
    ];

    /**
     * 处理记录event log
     * @param $params
     * @throws Exception
     */
    public function run(&$params)
    {
        if (empty($params['id'])) {
            return;
        }
        $task = model(TaskModel::class)->field('id,project_id,json')->find($params['id']);
        if (empty($task['project_id'])) {
            return;
        }
        $updateData = json_decode($params['json'] ?? '{}', true);
        if (empty($updateData['task_status'])) {
            return;
        }
        $updateIdStatus = StatusService::getInstance()->byCodeMap($this->updateCodeStatus);
        $updateIdStatus = array_column($updateIdStatus, 'id');

        if (!in_array($updateData['task_status'], $updateIdStatus)) {
            return;
        }
        $project = model(ProjectModel::class)->field('type')->find($task['project_id']);
        //甲方更新乙方
        if ($project['type'] != 'insource') {
            return;
        }
        $taskData = OrderService::getInstance()->getOutsideTaskByTaskId($task['id']);
        if (empty($taskData['id'])) {
            return;
        }
        $data['id'] = $taskData['id'];
        $data['task_status'] = $updateData['task_status'];
        try {
            CommonService::instance('task')->setCurrentModuleCode('task')->update($data, 'task', false);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
